package net.marvinlee.thestar;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Vector;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.DateUtils;
 
import net.marvinlee.parser.ChannelRefresh;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ChannelListFeedActivity  extends ListActivity { 
	private LayoutInflater mInflater;
	private Vector<RowData> data;
	protected ProgressDialog mBusy;	
	final Handler mHandler = new Handler();
	boolean changeViewPost = false;
	WebView webview; 
	String currentFeedTitle;
	String currentFeed;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.main);
		//Log.i("TheStar", "Init");
		mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

		Bundle dataBundle = (savedInstanceState == null)
								? getIntent().getExtras()
								: savedInstanceState;
		String selectedFeed = dataBundle.getString("feedUrl"); 
		currentFeed = selectedFeed;
		String selectedFeedTitle = dataBundle.getString("feedTitle"); 
		currentFeedTitle = selectedFeedTitle;
		Log.i("TheStar", "selectedFeed:" + selectedFeed);
		if (selectedFeed != null)
		{
			getFeed(data, selectedFeed); 
			getIntent().putExtra("feedTitle", selectedFeedTitle);
			getIntent().putExtra("feedList", data);
	        
		}
		else
		{ 
			Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("No Feed");
			builder.setMessage("Select a channel first");
			builder.setPositiveButton("OK", null);
			builder.show();
		} 
 	    
	}

	private void getFeed(Vector<RowData> data2, String feed) { 
		
		mBusy = ProgressDialog.show(this,
				"Downloading", "Accessing XML feed...", false, true);
		View progressView = mInflater.inflate(R.layout.progressbar, null);
		final ProgressBar progressBar = (ProgressBar)progressView.findViewById(R.id.progress_horizontal);
		final TextView progressText = (TextView)progressView.findViewById(R.id.progress_text);
		mBusy.setContentView(progressView);
		mBusy.setButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int which) {
						mBusy.cancel();
					} 
				}); 
		mBusy.setOnCancelListener(new OnCancelListener(){
			public void onCancel(DialogInterface dialog) {
				// TODO Auto-generated method stub
				mBusy.dismiss();
				finish(); 
			}  
			} 
		);
		Button progressButton = (Button)progressView.findViewById(R.id.cancel);
		progressButton.setOnClickListener(new OnClickListener()
				{ 
					public void onClick(View arg0) {
						 mBusy.dismiss();
						 finish();
					} 
		});

		final String rssurl = feed;
		Thread t = new Thread()
		{
			public void run()
			{
				try
				{					

					ChannelRefresh refresh = new ChannelRefresh(getContentResolver());
					//String rssurl = "http://thestar.com.my/rss/nation.xml";
					data = new Vector<RowData>();
					refresh.getFeed(null,  rssurl, data, getApplicationContext(), progressBar, progressText); 
					Log.i("TheStar", "Data added"); 
					
			    	mHandler.post(new Runnable() {
			    		public void run()
			    		{
							CustomAdapter adapter = new CustomAdapter(ChannelListFeedActivity.this, R.layout.custom_row,
									R.id.item, data);

							//Log.i("TheStar", "CustomAdapter initialized");
							setListAdapter(adapter);

							//Log.i("TheStar", "Setting other props");
							getListView().setTextFilterEnabled(true);
			    			mBusy.dismiss();
			    			 
			    		}
			    	});
				}
				catch(Exception e)
				{
					Log.d("::Exception::", e.toString());
					final String errmsg = e.getMessage();
					final String errmsgFull = e.toString();

		    		mHandler.post(new Runnable() {
		    			public void run()
		    			{
		    				mBusy.dismiss();

		    				String errstr = ((errmsgFull != null) ? errmsgFull : errmsg);

		    				new AlertDialog.Builder(ChannelListFeedActivity.this)
		    					.setTitle("Feed Error")
		    					.setMessage("An error was encountered while accessing the feed: " + errstr)
		    					.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		    						//whatever.
		    						public void onClick(DialogInterface dialog, int whichButton) {
		    							
		    						}
		    					}).create();
		    			}
		    		});
				}			    	
			}
		};

		t.start();		
	}
	private class CustomAdapter extends ArrayAdapter<RowData> {

		public CustomAdapter(Context context, int resource,
				int textViewResourceId, List<RowData> objects) {
			super(context, resource, textViewResourceId, objects);

		}
 
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			//Log.i("TheStar", "getView called");
			ViewHolder holder = null;

			// widgets displayed by each item in your list
			TextView item = null;
			WebView description = null;
			Button moreLink = null;
			TextView publishedDate = null;

			// data from your adapter
			//Log.i("TheStar", "getView : getItem(position)" + position);
			RowData rowData = getItem(position); 

			// we want to reuse already constructed row views...
			if (null == convertView) {
  
				convertView = mInflater.inflate(R.layout.custom_row, null);
				holder = new ViewHolder(convertView);
				convertView.setTag(holder); 
			}
			// 
			holder = (ViewHolder) convertView.getTag(); 
			item = holder.getItem();
			//item.loadData("<b>"+rowData.mTitle+"</b>", "text/html", "UTF-8");
			item.setText(rowData.mTitle);
			item.setBackgroundColor(Color.WHITE);
			item.setTextColor(Color.BLACK);
			
			final String link = rowData.mUrl; 
			/*
			item.setOnTouchListener(new OnTouchListener() { 
				public boolean onTouch(View view, MotionEvent arg1) {
					Log.i("TheStar", "onClick called");
					changeViewPost = true;
					
					//Now we change to call activity instead

					Intent postIntent = new Intent(getApplicationContext(), ViewPostTabActivity.class);
					postIntent.putExtra("feedTitle", currentFeedTitle );
					postIntent.putExtra("postUrl", link);
					startActivity(postIntent);
					 
					return false;
				} 
				
			});*/

			description = holder.getDescription();
			description.loadDataWithBaseURL("http://www.thestar.com.my", rowData.mDescription, "text/html", "UTF-8", "");
			//description.setText(StringEscapeUtils.unescapeHtml(rowData.mDescription));
			 
			
			moreLink = holder.getMoreLink();
			moreLink.setText("[ More >> ]");
			moreLink.setBackgroundColor(Color.WHITE);
			//moreLink.setTextColor(Color.BLACK);
			final Button moreLinkInstance = moreLink;
			moreLink.setOnTouchListener(new OnTouchListener() { 
				public boolean onTouch(View view, MotionEvent arg1) {
					//Log.i("TheStar", "onClick called");
					changeViewPost = true;
					
					moreLinkInstance.setBackgroundColor(Color.GRAY);
					try {
						Thread.sleep(500);
						//moreLinkInstance.setBackgroundColor(Color.WHITE);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					//Now we change to call activity instead

					Intent postIntent = new Intent(getApplicationContext(), ViewPostTabActivity.class);
					postIntent.putExtra("feedTitle", currentFeedTitle );
					postIntent.putExtra("postUrl", link);
					startActivity(postIntent);

					return false;
				} 
				
			});
			 
			publishedDate = holder.getPublishedDate();
			publishedDate.setText(rowData.mDate);
			publishedDate.setBackgroundColor(Color.WHITE);
			publishedDate.setTextColor(Color.BLACK);
			
			return convertView;
		}
 
	}

	/**
	 * Wrapper for row data.
	 * 
	 */
	private class ViewHolder {
		private View mRow;
		private WebView description = null;
		private TextView item = null;
		private Button moreLink = null;
		private TextView pDate = null; 

		public ViewHolder(View row) {
			mRow = row;
		}

		public WebView getDescription() {
			if (null == description) {
				description = (WebView) mRow.findViewById(R.id.description);
			}
			return description;
		}

		public TextView getItem() {
			if (null == item) {
				item = (TextView) mRow.findViewById(R.id.item);
			}
			return item;
		}

		public Button getMoreLink() {
			if (null == moreLink) {
				moreLink = (Button) mRow.findViewById(R.id.more);
			}
			return moreLink;
		}
		
		public TextView getPublishedDate() {
			if (null == pDate) {
				pDate = (TextView) mRow.findViewById(R.id.p_date);
			}
			return pDate;
		}
	} 
	 
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if (webview != null)
    	{
	        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
	            webview.goBack();
	            return true;
	        }
    	}
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onContentChanged()
    {
    	if (!changeViewPost){
            //Log.i("TheStar", "onContentChanged notChangeViewPost");
	    	//donothing
	    	super.onContentChanged();
    	}
    	else
    	{

            //Log.i("TheStar", "onContentChanged IS changeViewPost");
    	}
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
	    super.onSaveInstanceState(outState); 
	    //Log.d("TheStar", "Screen is rotated");
		outState.putString("feedUrl", currentFeed); 
		outState.putString("feedTitle", currentFeedTitle); 
		String selectedFeed = outState.getString("feedUrl"); 
		String selectedFeedTitle = outState.getString("feedTitle");  
	    Log.d("TheStar", "Feed title rotated:"+ selectedFeedTitle + " feed:" + selectedFeed); 
    }
}
